package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopTypeMapper shopTypeMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public  Result queryTypeList() throws JsonProcessingException {
        //从缓存中查询信息
        String ShopListJOSNString  = stringRedisTemplate.opsForValue().get(RedisConstants.SHOP_LIST);
        //若未找到，则从数据库中查找
        if(ShopListJOSNString == null){
             List<ShopType> shopTypeList = shopTypeMapper.select();
             if(shopTypeList == null){
                  return Result.fail("分类为空");
             }

             String Josn = objectMapper.writeValueAsString(shopTypeList);
             //将数据存入缓存中
             stringRedisTemplate.opsForValue().set(RedisConstants.SHOP_LIST,Josn);
             return Result.ok(shopTypeList);
        }
        //若找到，这直接从缓存中读取
        List<ShopType> shopTypeList = objectMapper.readValue(ShopListJOSNString, new TypeReference<List<ShopType>>() {});
        return Result.ok(shopTypeList);




    }
}
